﻿#ifndef HSV_CONVERTER
#define HSV_CONVERTER

    #define EPSILON         1.0e-4
    void RgbToHsv(in real3 color, out real3 hsv)
    {
        real4 K = real4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0);
        real4 p = lerp(real4(color.bg, K.wz), real4(color.gb, K.xy), step(color.b, color.g));
        real4 q = lerp(real4(p.xyw, color.r), real4(color.r, p.yzx), step(p.x, color.r));
        real d = q.x - min(q.w, q.y);
        real e = EPSILON;
        hsv = real3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);
    }
    
    void HsvToRgb(in real3 hsv, out real3 color)
    {
        real4 K = real4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
        real3 p = abs(frac(hsv.xxx + K.xyz) * 6.0 - K.www);
        color = hsv.z * lerp(K.xxx, saturate(p - K.xxx), hsv.y);
    }

    #define RgbToHsv_half(col,hsv) RgbToHsv(col,hsv)
    #define RgbToHsv_float(col,hsv) RgbToHsv(col,hsv)

    #define HsvToRgb_half(hsv,col) HsvToRgb(hsv,col)
    #define HsvToRgb_float(hsv,col) HsvToRgb(hsv,col)

#endif